<template>
  <div class="admin-score-lines">
    <!-- 头部工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        新增分数线
      </el-button>
      <el-button type="success" @click="showImportDialog">
        <el-icon><Upload /></el-icon>
        批量导入
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedItems.length">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="院校">
          <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
            <el-option 
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="searchForm.majorId" placeholder="选择专业" clearable>
            <el-option 
              v-for="major in majors"
              :key="major.id"
              :label="major.name"
              :value="major.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年份">
          <el-select v-model="searchForm.year" placeholder="选择年份" clearable>
            <el-option 
              v-for="year in years"
              :key="year"
              :label="year"
              :value="year"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="批次">
          <el-select v-model="searchForm.batch" placeholder="选择批次" clearable>
            <el-option 
              v-for="batch in batches"
              :key="batch"
              :label="batch"
              :value="batch"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadScoreLines">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="year" label="年份" width="80" />
      <el-table-column prop="schoolName" label="院校" />
      <el-table-column prop="majorName" label="专业" />
      <el-table-column prop="batch" label="批次" width="100" />
      <el-table-column prop="subjectType" label="科目类型" width="100" />
      <el-table-column label="分数" width="180">
        <template #default="scope">
          <div>
            <span class="score-item">最低: {{ scope.row.minScore || '-' }}</span>
            <span class="score-item">最高: {{ scope.row.maxScore || '-' }}</span>
            <span class="score-item">平均: {{ scope.row.avgScore ? scope.row.avgScore.toFixed(1) : '-' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="planCount" label="计划数" width="80" />
      <el-table-column prop="admitCount" label="录取数" width="80" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" class="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadScoreLines"
        @current-change="loadScoreLines"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle"
      v-model="dialogVisible"
      width="700px"
      @close="resetForm"
    >
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="formRef"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="院校" prop="schoolId">
              <el-select v-model="formData.schoolId" placeholder="选择院校">
                <el-option 
                  v-for="school in schools"
                  :key="school.id"
                  :label="school.name"
                  :value="school.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业">
              <el-select v-model="formData.majorId" placeholder="选择专业" clearable>
                <el-option 
                  v-for="major in majors"
                  :key="major.id"
                  :label="major.name"
                  :value="major.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年份" prop="year">
              <el-input-number v-model="formData.year" :min="2020" :max="2030" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次">
              <el-input v-model="formData.batch" placeholder="如：专科" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="科目类型">
              <el-input v-model="formData.subjectType" placeholder="如：文科" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="最低分数">
              <el-input-number v-model="formData.minScore" :min="0" :max="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最高分数">
              <el-input-number v-model="formData.maxScore" :min="0" :max="1000" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="位次信息">
              <el-input v-model="formData.rankInfo" placeholder="位次信息" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="招生计划数">
              <el-input-number v-model="formData.planCount" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="录取人数">
              <el-input-number v-model="formData.admitCount" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input 
            v-model="formData.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Delete } from '@element-plus/icons-vue'

export default {
  name: 'AdminScoreLines',
  components: {
    Plus,
    Upload,
    Delete
  },
  setup() {
    const loading = ref(false)
    const tableData = ref([])
    const selectedItems = ref([])
    const schools = ref([])
    const majors = ref([])
    const years = ref([])
    const batches = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      schoolId: null,
      majorId: null,
      year: null,
      batch: ''
    })

    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })

    // 对话框
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)
    
    // 表单
    const formRef = ref(null)
    const formData = reactive({
      schoolId: null,
      majorId: null,
      year: new Date().getFullYear(),
      batch: '',
      subjectType: '',
      minScore: null,
      maxScore: null,
      rankInfo: '',
      planCount: null,
      admitCount: null,
      remark: '',
      status: 1
    })

    const formRules = {
      schoolId: [{ required: true, message: '请选择院校', trigger: 'change' }],
      year: [{ required: true, message: '请选择年份', trigger: 'blur' }]
    }

    // 加载基础数据
    const loadBasicData = async () => {
      try {
        // 模拟数据，实际应该调用对应的API
        schools.value = [
          { id: 1, name: '浙江工贸职业技术学院' },
          { id: 2, name: '浙江机电职业技术学院' }
        ]
        
        majors.value = [
          { id: 1, name: '计算机应用技术', schoolId: 1 },
          { id: 2, name: '机械制造与自动化', schoolId: 2 }
        ]

        years.value = [2024, 2023, 2022, 2021, 2020]
        batches.value = ['专科', '本科']
      } catch (error) {
        console.error('加载基础数据失败:', error)
      }
    }

    // 加载分数线列表
    const loadScoreLines = async () => {
      loading.value = true
      try {
        // 模拟数据，实际应该调用API
        const mockData = {
          records: [
            {
              id: 1,
              schoolId: 1,
              majorId: 1,
              year: 2024,
              batch: '专科',
              subjectType: '综合',
              minScore: 380,
              maxScore: 520,
              avgScore: 450,
              planCount: 50,
              admitCount: 48,
              status: 1,
              schoolName: '浙江工贸职业技术学院',
              majorName: '计算机应用技术'
            }
          ],
          total: 1
        }
        
        tableData.value = mockData.records || []
        pagination.total = mockData.total || 0
      } catch (error) {
        console.error('加载分数线列表失败:', error)
        ElMessage.error('加载分数线列表失败')
      } finally {
        loading.value = false
      }
    }

    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        schoolId: null,
        majorId: null,
        year: null,
        batch: ''
      })
      pagination.page = 1
      loadScoreLines()
    }

    // 显示新增对话框
    const showCreateDialog = () => {
      dialogTitle.value = '新增分数线'
      isEdit.value = false
      dialogVisible.value = true
      resetForm()
    }

    // 显示导入对话框
    const showImportDialog = () => {
      ElMessage.info('批量导入功能开发中...')
    }

    // 编辑
    const handleEdit = (row) => {
      dialogTitle.value = '编辑分数线'
      isEdit.value = true
      dialogVisible.value = true
      Object.assign(formData, row)
    }

    // 查看详情
    const handleView = (row) => {
      ElMessage.info('查看功能开发中...')
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除${row.year}年${row.schoolName}的分数线数据吗？`,
          '确认删除',
          { type: 'warning' }
        )
        
        // 调用删除API
        ElMessage.success('删除成功')
        loadScoreLines()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 批量删除
    const handleBatchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的${selectedItems.value.length}条分数线数据吗？`,
          '确认删除',
          { type: 'warning' }
        )
        
        // 调用批量删除API
        ElMessage.success('批量删除成功')
        loadScoreLines()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }

    // 选择变更
    const handleSelectionChange = (selection) => {
      selectedItems.value = selection
    }

    // 保存
    const handleSave = async () => {
      try {
        await formRef.value.validate()
        
        if (isEdit.value) {
          // 调用更新API
          ElMessage.success('更新成功')
        } else {
          // 调用创建API
          ElMessage.success('创建成功')
        }
        
        dialogVisible.value = false
        loadScoreLines()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(formData, {
        schoolId: null,
        majorId: null,
        year: new Date().getFullYear(),
        batch: '',
        subjectType: '',
        minScore: null,
        maxScore: null,
        rankInfo: '',
        planCount: null,
        admitCount: null,
        remark: '',
        status: 1
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    onMounted(() => {
      loadBasicData()
      loadScoreLines()
    })

    return {
      loading,
      tableData,
      selectedItems,
      schools,
      majors,
      years,
      batches,
      searchForm,
      pagination,
      dialogVisible,
      dialogTitle,
      isEdit,
      formRef,
      formData,
      formRules,
      loadScoreLines,
      resetSearch,
      showCreateDialog,
      showImportDialog,
      handleEdit,
      handleView,
      handleDelete,
      handleBatchDelete,
      handleSelectionChange,
      handleSave,
      resetForm
    }
  }
}
</script>

<style scoped>
.admin-score-lines {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
}

.search-form {
  background: #f5f5f5;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.danger {
  color: #f56c6c;
}

.score-item {
  display: block;
  font-size: 12px;
  line-height: 1.4;
}
</style>